package com.smart.auth.service.impl;


import com.smart.auth.entity.User;
import com.smart.auth.service.UserService;
import com.smart.auth.util.RequestUtils;
import com.smart.common.bean.pojo.dto.UserDTO;
import com.smart.common.enums.ResultCodeEnum;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * 自定义用户认证和授权
 */
@SuppressWarnings("AlibabaSwitchStatement")
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    UserService userService;

//    private UserFeignService userFeignService;
//    private UmsMemberFeignService memberFeignService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = RequestUtils.getAuthClientId();
        com.smart.common.bean.entity.User vo = userService.getUserByUsername(username);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(vo, userDTO);
        if (userDTO == null) {
            throw new UsernameNotFoundException(ResultCodeEnum.ACCOUNT_NOT_EXIST.getMessage());
        }
        User user = new User(userDTO);
        if (!user.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!user.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }
        return user;
    }

}
